package com.ikingtech.platform.service.system.dept.service;

import com.ikingtech.framework.sdk.department.api.DeptUserApi;
import com.ikingtech.framework.sdk.department.model.DeptManagerDTO;
import com.ikingtech.framework.sdk.user.api.UserDeptApi;
import com.ikingtech.framework.sdk.user.model.UserDeptDTO;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.system.dept.entity.DepartmentDO;
import com.ikingtech.platform.service.system.dept.service.repository.DeptRepository;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
@RequiredArgsConstructor
public class UserDeptService implements UserDeptApi {

    private final DeptRepository repo;

    private final DeptUserApi deptUserApi;

    /**
     * 根据部门ID列表加载部门信息
     * @param deptIds 部门ID列表
     * @return 部门信息列表
     */
    @Override
    public List<UserDeptDTO> loadByIds(List<String> deptIds) {
        if (Tools.Coll.isBlank(deptIds)) {
            return new ArrayList<>();
        }
        // 根据部门ID列表查询部门实体列表
        List<DepartmentDO> entities = this.repo.listByIds(deptIds);
        if (Tools.Coll.isBlank(entities)) {
            return new ArrayList<>();
        }
        // 根据部门实体列表加载部门负责人信息列表
        List<DeptManagerDTO> deptManagers = this.deptUserApi.loadManagers(Tools.Coll.convertList(entities, DepartmentDO::getManagerId));
        // 将部门负责人信息列表转换为部门负责人ID和负责人信息的映射表
        Map<String, DeptManagerDTO> deptManagerMap = Tools.Coll.convertMap(deptManagers, DeptManagerDTO::getUserId);
        // 根据部门实体列表转换为部门信息列表
        return Tools.Coll.convertList(entities, entity -> {
            UserDeptDTO userDept = new UserDeptDTO();
            userDept.setDeptId(entity.getId());
            userDept.setDeptName(entity.getName());
            userDept.setDeptFullPath(entity.getFullPath());
            // 如果部门负责人ID存在，则加载部门负责人信息
            if (deptManagerMap.containsKey(entity.getManagerId())) {
                userDept.setManagerId(deptManagerMap.get(entity.getManagerId()).getUserId());
                userDept.setManagerName(deptManagerMap.get(entity.getManagerId()).getUserName());
                userDept.setManagerAvatar(deptManagerMap.get(entity.getManagerId()).getUserAvatar());
            }
            return userDept;
        });
    }
}
